package cn.stylefeng.guns.modular.business.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.stylefeng.guns.modular.business.comment.YunHeKey;
import cn.stylefeng.guns.modular.business.entity.HeritageInfo;
import cn.stylefeng.guns.modular.business.entity.SubDic;
import cn.stylefeng.guns.modular.business.enums.HeritageInfoExceptionEnum;
import cn.stylefeng.guns.modular.business.mapper.HeritageInfoMapper;
import cn.stylefeng.guns.modular.business.pojo.HeritageInfoRequest;
import cn.stylefeng.guns.modular.business.service.HeritageInfoService;
import cn.stylefeng.guns.modular.business.service.SubUseBrowseService;
import cn.stylefeng.roses.kernel.auth.api.LoginUserApi;
import cn.stylefeng.roses.kernel.auth.api.pojo.login.LoginUser;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.roses.kernel.rule.util.HttpServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 遗产业务实现层
 *
 * @author zhangyaowen
 * @date 2021/11/05 15:32
 */
@Service
public class HeritageInfoServiceImpl extends ServiceImpl<HeritageInfoMapper, HeritageInfo> implements HeritageInfoService {

    @Resource
    private LoginUserApi loginUserApi;
    @Resource
    private SubUseBrowseService subUseBrowseService;
    
	@Override
    public void add(HeritageInfoRequest heritageInfoRequest) {
        HeritageInfo heritageInfo = new HeritageInfo();
        BeanUtil.copyProperties(heritageInfoRequest, heritageInfo);
        this.save(heritageInfo);
    }

    @Override
    public void del(HeritageInfoRequest heritageInfoRequest) {
        HeritageInfo heritageInfo = this.queryHeritageInfo(heritageInfoRequest);
        this.removeById(heritageInfo.getId());
    }

    @Override
    public void edit(HeritageInfoRequest heritageInfoRequest) {
        HeritageInfo heritageInfo = this.queryHeritageInfo(heritageInfoRequest);
        BeanUtil.copyProperties(heritageInfoRequest, heritageInfo);
        this.updateById(heritageInfo);
    }

    @Override
    public HeritageInfo detail(HeritageInfoRequest heritageInfoRequest) {
        return this.queryHeritageInfo(heritageInfoRequest);
    }

    @Override
    public PageResult<Map<String, Object>> findPage(String value,String heritage,String heritageType) {
        String[] heritages = {};
        if(!heritage.equals("") ) {
            heritages = StrUtil.splitToArray(heritage, ";");
        }
        LambdaQueryWrapper<HeritageInfo> wrapper = createWrappereByChoose(heritages,value,heritageType);
        Page<HeritageInfo> sysRolePage = this.page(PageFactory.defaultPage(), wrapper);
        PageResult<HeritageInfo> heritageInfoPageResult = PageResultFactory.createPageResult(sysRolePage);
        List<HeritageInfo> list = heritageInfoPageResult.getRows();
        PageResult<Map<String, Object>> pageResult = new PageResult<>();
        List<Map<String,Object>> mapList = new ArrayList<>();
        for(HeritageInfo heritageInfo : list){
            Map<String, Object> map = new HashMap<String, Object>();
//            map = JSONObject.parseObject(JSONObject.toJSONString(HeritageInfo), Map.class);
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
            String jmid = YunHeKey.YCKG+heritageInfo.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
            map.put("title",heritageInfo.getShiTitle());
            map.put("theCommon",heritageInfo.getTheCommon());
            map.put("historyDating",heritageInfo.getHistoryDating());
            map.put("annalsfrom",heritageInfo.getShiAnnalsfrom());
            mapList.add(map);
        }
        pageResult.setRows(mapList);
        pageResult.setPageNo(heritageInfoPageResult.getPageNo());
        pageResult.setTotalRows(heritageInfoPageResult.getTotalRows());
        pageResult.setPageSize(heritageInfoPageResult.getPageSize());
        pageResult.setTotalPage(heritageInfoPageResult.getTotalPage());
        return pageResult;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/08/30 10:17
     */
    private LambdaQueryWrapper<HeritageInfo> createWrappereByChoose(String[] heritages, String value,String heritageType) {
        LambdaQueryWrapper<HeritageInfo> queryWrapper = new LambdaQueryWrapper<HeritageInfo>();
        queryWrapper.and(i-> i.eq(ObjectUtil.isNotNull(heritageType), HeritageInfo::getShiHeritage, heritageType).or()
                .like(ObjectUtil.isNotNull(value), HeritageInfo::getShiTitle, value).or()
                .like(ObjectUtil.isNotNull(value), HeritageInfo::getTheCommon, value).or()
                .like(ObjectUtil.isNotNull(value), HeritageInfo::getHistoryDating, value).or()
                .like(ObjectUtil.isNotNull(value), HeritageInfo::getShiAnnalsfrom, value));
        if( heritages.length !=0 ) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < heritages.length; i++) {
                    String time = heritages[i];
                    wrapper.like(ObjectUtil.isNotEmpty(time), HeritageInfo::getShiFirst, time);
                    if (i != heritages.length - 1) {
                        wrapper.or();
                    }
                }
            });
        }
        return queryWrapper.orderByDesc(HeritageInfo::getId);
    }

    @Override
    public List<HeritageInfo> findList(HeritageInfoRequest heritageInfoRequest) {
        LambdaQueryWrapper<HeritageInfo> wrapper = this.createWrapper(heritageInfoRequest);
        return this.list(wrapper);
    }

    /**
     * 获取信息
     *
     * @author zhangyaowen
     * @date 2021/11/05 15:32
     */
    private HeritageInfo queryHeritageInfo(HeritageInfoRequest heritageInfoRequest) {
        HeritageInfo heritageInfo = this.getById(heritageInfoRequest.getId());
        if (ObjectUtil.isEmpty(heritageInfo)) {
            throw new ServiceException(HeritageInfoExceptionEnum.HERITAGEINFO_NOT_EXISTED);
        }
        return heritageInfo;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/11/05 15:32
     */
    private LambdaQueryWrapper<HeritageInfo> createWrapper(HeritageInfoRequest heritageInfoRequest) {
        LambdaQueryWrapper<HeritageInfo> queryWrapper = new LambdaQueryWrapper<>();

        Long id = heritageInfoRequest.getId();
        String shiHeritage = heritageInfoRequest.getShiHeritage();
        String shiFirst = heritageInfoRequest.getShiFirst();
        String shiSecond = heritageInfoRequest.getShiSecond();
        String shiThird = heritageInfoRequest.getShiThird();
        String shiPeriod = heritageInfoRequest.getShiPeriod();
        String historyDating = heritageInfoRequest.getHistoryDating();
        String theCommon = heritageInfoRequest.getTheCommon();
        String shiIntroduce = heritageInfoRequest.getShiIntroduce();
        String shiAnnotation = heritageInfoRequest.getShiAnnotation();
        String shiAnnalsfrom = heritageInfoRequest.getShiAnnalsfrom();
        String shiAnnalspage = heritageInfoRequest.getShiAnnalspage();

        queryWrapper.eq(ObjectUtil.isNotNull(id), HeritageInfo::getId, id);
        queryWrapper.like(ObjectUtil.isNotEmpty(shiHeritage), HeritageInfo::getShiHeritage, shiHeritage);
        queryWrapper.like(ObjectUtil.isNotEmpty(shiFirst), HeritageInfo::getShiFirst, shiFirst);
        queryWrapper.like(ObjectUtil.isNotEmpty(shiSecond), HeritageInfo::getShiSecond, shiSecond);
        queryWrapper.like(ObjectUtil.isNotEmpty(shiThird), HeritageInfo::getShiThird, shiThird);
        queryWrapper.like(ObjectUtil.isNotEmpty(shiPeriod), HeritageInfo::getShiPeriod, shiPeriod);
        queryWrapper.like(ObjectUtil.isNotEmpty(historyDating), HeritageInfo::getHistoryDating, historyDating);
        queryWrapper.like(ObjectUtil.isNotEmpty(theCommon), HeritageInfo::getTheCommon, theCommon);
        queryWrapper.like(ObjectUtil.isNotEmpty(shiIntroduce), HeritageInfo::getShiIntroduce, shiIntroduce);
        queryWrapper.like(ObjectUtil.isNotEmpty(shiAnnotation), HeritageInfo::getShiAnnotation, shiAnnotation);
        queryWrapper.like(ObjectUtil.isNotEmpty(shiAnnalsfrom), HeritageInfo::getShiAnnalsfrom, shiAnnalsfrom);
        queryWrapper.like(ObjectUtil.isNotEmpty(shiAnnalspage), HeritageInfo::getShiAnnalspage, shiAnnalspage);

        return queryWrapper;
    }

    @Override
    public List<Map<String,Object>> heritageType() {
        LambdaQueryWrapper<HeritageInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(HeritageInfo::getShiFirst);
        List<HeritageInfo>  heritageInfoList = this.list(queryWrapper);
        List<String> heritageInfoList2 = heritageInfoList.stream().map(HeritageInfo::getShiFirst).distinct().collect(Collectors.toList());
        List<Map<String,Object>> findList = new ArrayList<>();
        Map<String, Object> findHeritage = new HashMap<String, Object>();
        List<Map<String,Object>> mapList = new ArrayList<>();
        for(String sss : heritageInfoList2){
            Map<String, Object> map1 = new HashMap<String, Object>();
            if("".equals(sss) || sss == null){
                continue;
            }else{
                map1.put("heritage", sss);
                mapList.add(map1);
            }
        }
        findHeritage.put("list",mapList);
        findHeritage.put("title","遗产分类");
        findList.add(findHeritage);
        return findList;
    }

    @Override
    public Map<String, Object> toReview(String jmId) {
        byte[] key =YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        String decryptStr = aes.decryptStr(jmId, CharsetUtil.CHARSET_UTF_8);
        //获取ID字符串YHSJ后面真实的的id
        String id = StrUtil.subAfter(decryptStr,YunHeKey.YCKG,false);
        HttpServletRequest request = HttpServletUtil.getRequest();
        Long userid;
        if (ObjectUtil.isNotNull(request)) {

            LoginUser loginUser = loginUserApi.getLoginUser();
            userid = loginUser.getUserId();
        } else {
            throw new ServiceException(HeritageInfoExceptionEnum.REQUEST_EMPTY);
        }
        LambdaQueryWrapper<HeritageInfo> queryWrapper = new LambdaQueryWrapper<>();
        if ("".equals(id)) {
            Map<String, Object> mapLists = new HashMap<>();
            return mapLists;
        }
        queryWrapper.eq(ObjectUtil.isNotEmpty(id), HeritageInfo::getId, id);
        List<HeritageInfo> HeritageInfoList = this.list(queryWrapper);


        Map<String, Object> mapL = new HashMap<>();
        for (HeritageInfo HeritageInfo : HeritageInfoList) {

            Map<String, Object> map = new HashMap<String, Object>();
            map = JSONObject.parseObject(JSONObject.toJSONString(HeritageInfo), Map.class);

            // 获取类的属性
            Field[] declaredFields = HeritageInfo.class.getDeclaredFields();
            List<Map<String, Object>> mplist = new ArrayList<>();
            // 遍历属性，获取属性上ApiModelProperty的值，属性的名，存入Properties
            if (declaredFields.length != 0) {
//                String title = "";
                int i = 1;
                Map<String, Object> p = new HashMap<String, Object>();
                for (Field field : declaredFields) {

                    Map<String, Object> mp = new HashMap<String, Object>();
                    if (field.getAnnotation(ApiModelProperty.class) != null) {
                        //获取注解属性
                        ApiModelProperty aa = field.getAnnotation(ApiModelProperty.class);
                        // key和value可根据需求存
                        // 这存的key为注解的值，value为类属性名

                        if ("shiTitle".equals(field.getName()) || "shiIntroduce".equals(field.getName()) || "shiAnnotation".equals(field.getName()) ) {
                            if ("shiTitle".equals(field.getName()) ) {
                                p.put("title", map.get(field.getName()));
                            }else if("shiAnnotation".equals(field.getName())){
                                p.put("annotation", map.get(field.getName()));
                            }
                            else {
                                p.put(field.getName(), map.get(field.getName()));
                            }
                        }else{
                            mp.put("key", aa.value());
                            mp.put("value", map.get(field.getName()));
                            if (i != 1) {
                                mplist.add(mp);
                            }
                        }
                    }
                    i++;
                }
                p.put("list", mplist);
                if (i != 1) {
                    mapL.putAll(p);
                }
            }
        }
        if(userid != 0l && userid != -1l) {
            subUseBrowseService.saveBrowse(YunHeKey.YHYC,mapL.get("title").toString(),userid,request);
        }
        return mapL;
    }


    @Override
    public List<Map<String,Object>> findAllList(List<SubDic> riverList, List<SubDic> townList, String[] times, String name) {
        LambdaQueryWrapper<HeritageInfo> wrapper = createWrapperByTown(riverList,townList,times,name);
        List<HeritageInfo>  list = this.list(wrapper);
        List<Map<String,Object>> mapList=new ArrayList<>();
        for(HeritageInfo HeritageInfo:list) {
            Map<String, Object> map = new HashMap<String, Object>();

            map.put("title", HeritageInfo.getShiTitle());
            map.put("historyDating",HeritageInfo.getHistoryDating());
            map.put("theCommon",HeritageInfo.getTheCommon());
            map.put("from",HeritageInfo.getShiAnnalsfrom() );
            map.put("createTime", DateUtil.format(HeritageInfo.getCreateTime(), "yyyy-MM-dd"));
            map.put("type",YunHeKey.YCKG);
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

            String jmid = YunHeKey.YCKG+HeritageInfo.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/08/30 10:17
     */
    private LambdaQueryWrapper<HeritageInfo> createWrapperByTown(List<SubDic> riverList, List<SubDic> townList, String[] times, String name) {
        LambdaQueryWrapper<HeritageInfo> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.and(i-> i.like(ObjectUtil.isNotNull(name), HeritageInfo::getShiTitle, name).or()
                .like(ObjectUtil.isNotNull(name), HeritageInfo::getShiAnnalsfrom, name).or()
                .like(ObjectUtil.isNotNull(name), HeritageInfo::getTheCommon, name).or()
                .like(ObjectUtil.isNotNull(name), HeritageInfo::getHistoryDating, name).or());
        if( !riverList.isEmpty()) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < riverList.size(); i++) {
                    String dicAname = riverList.get(i).getDicAname();
                    wrapper.like(ObjectUtil.isNotEmpty(dicAname), HeritageInfo::getXgRiver, dicAname);
                    if (i != riverList.size() - 1) {
                        wrapper.or();
                    }
                }
            });
        }
        if( !townList.isEmpty()) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < townList.size(); i++) {
                    String dicZname = townList.get(i).getDicZname();
                    wrapper.like(ObjectUtil.isNotEmpty(dicZname), HeritageInfo::getXgTown, dicZname);
                    if (i != townList.size() - 1) {
                        wrapper.or();
                    }
                }
            });
        }
        if( times.length !=0) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < times.length; i++) {
                    String time = times[i];
                    wrapper.like(ObjectUtil.isNotEmpty(time), HeritageInfo::getShiPeriod, time);
                    if (i != times.length - 1) {
                        wrapper.or();
                    }
                }
            });
        }
        return queryWrapper;
    }


}